import 'package:flutter/material.dart';

class AttributedLabel extends StatelessWidget {
  final String text;
  final Map<String, String> replacements;
  final TextStyle style;

  const AttributedLabel({super.key, required this.text, required this.replacements, required this.style});

  @override
  Widget build(BuildContext context) {
    // 分割文本并构建 TextSpan 列表
    final spans = <InlineSpan>[];
    final regex = RegExp(replacements.keys.map(RegExp.escape).join('|'));
    text.splitMapJoin(
      regex,
      onMatch: (match) {
        // 如果是匹配到的关键词，用对应的替代 Widget
        final key = match[0]!;
        if (replacements.containsKey(key)) {
          spans.add(WidgetSpan(
            alignment: PlaceholderAlignment.middle,
            child: Image.asset(
              replacements[key]!,
              fit: BoxFit.cover,
              width: 18,
              height: 18,
            ),
          ));
        }
        return '';
      },
      onNonMatch: (nonMatch) {
        // 否则直接用文本
        spans.add(TextSpan(
          text: nonMatch,
          style: style,
        ));
        return '';
      },
    );

    return RichText(
      text: TextSpan(children: spans),
    );
  }
}
